// miniprogram/pages/applications/additem/additem.js
var app=getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    sort_list: [{
      name: '节日鲜花',
      id: 0,
      types: 1
    },
    {
      name: '鲜花花材',
      id: 1,
      types: 1
    },
    {
      name: '爱情鲜花',
      id: 2,
      types: 1
    },
    {
      name: '送花对象',
      id: 3,
      types: 1
    },
    {
      name: '鲜花类型',
      id: 4,
      types: 1
    },
    {
      name: '鲜花颜色',
      id: 5,
      types: 2
    },
    {
      name: '鲜花枝数',
      id: 6,
      types: 3
    },
    {
      name: '鲜花价格',
      id: 7,
      types: 4
    },
    {
      name: '花篮价格',
      id: 8,
      types: 4
    },
    {
      name: '开业/商务鲜花',
      id: 9,
      types: 1
    },
    {
      name: '企业鲜花',
      id: 10,
      types: 1
    },
    {
      name: '婚庆/婚礼',
      id: 11,
      types: 1
    },
    ],
    pics:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  getSortList(e) {
    let idx = e.currentTarget.dataset.idx;
    let sort = this.data.sort_list;
    this.setData({
      sid: idx,
      sort: sort[idx]
    })
    this.getTypeList();
  },
  getTypeIndex(e){
    let idx = e.currentTarget.dataset.idx;
    let types = this.data.type_list;
    this.setData({
      tid: idx,
      types: types[idx]
    })
  },
  getTypeList(){
    let db=wx.cloud.database();
    let name=this.data.sort.name;
    let _this=this;
    db.collection('tb_type_list').where({type_sort:name}).get({
      success:res=>{
        console.log(res)
        _this.setData({
          type_list:res.data
        })
      },
      fail:err=>{
        console.log(err)
      }
    })
  },
  formSubmit(e){
    console.log(e)
    let val=e.detail.value;
    this.setData({
      val:val
    })
    this.uploadMoreimgs();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //选取多张图片
  chooseDeltailImgs: function () {//这里是选取图片的方法
    var that = this;
    wx.chooseImage({
      count: 9 - this.data.pics.length, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        console.log(res);
        var imgsrc = res.tempFilePaths;
        var imgFiles = res.tempFiles;
        for (let i = 0; i < imgFiles.length; i++) {
          if (imgFiles[i].size > 5242880) {
            var msg = '第' + (i + 1) + '张图片大于5M,请上传小于5M的图片'
            wx.showModal({
              title: '消息提示',
              content: msg,
            })
            return false;
          }
        }
        var a = that.data.pics;
        if ((a.length + imgsrc.length) <= 9) {
          for (let i = 0; i < imgsrc.length; i++) {
            a.push(imgsrc[i]);
          }
        } else {
          wx.showToast({
            title: '图片上限9张',
          })
        }
        //console.log(a);
        that.setData({
          pics: a
        });
        // that.uploadimg();
        // that.setData({
        //     loadHide:false,
        //  })
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })

  },
  deleteAllImg(e) {
    console.log(e)
    var id = e.currentTarget.dataset.info;
    var pics = this.data.pics;
    pics.splice(id, 1);

    //  console.log(id);
    this.setData({
      pics: pics,
    })
  },
  uploadMoreimgs: function () {//这里触发图片上传的方法
    var pics = this.data.pics;
    var that = this;
    console.log(pics);
    this.uploadCloudFiles({
      //url: app.globalData.antiqueBaseUrl + 'qiniuUpload.html',//这里是你图片上传的接口
      path: pics//这里是选取的图片的地址数组
    })
  },
  //多张图片上传
  uploadCloudFiles(data) {
    wx.showLoading({
      title: '正在上传中',
    })
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    const filePath = data.path[i];
    console.log('filePath', filePath);
    // 上传图片
    var date = new Date();
    console.log(date);
    var yy = date.getFullYear();
    var mm = date.getMonth() + 1;
    var dd = date.getDate();
    const cloudPath = yy + '' + mm + '' + dd + '' + parseInt(Math.random() * 10000000) + filePath.match(/\.[^.]+?$/)[0];

    console.log('cloudPath', cloudPath);
    wx.cloud.uploadFile({
      cloudPath,
      filePath,
      success: res => {
        success++;
        console.log(res);
        app.globalData.dimgs.push(res.fileID);
        console.log('[上传文件] 成功：', res)
      },
      fail: e => {
        fail++;
        console.error('[上传文件] 失败：', e)
      },
      complete: () => {
        i++;
        if (i == data.path.length) { //当图片传完时，停止调用   
          console.log('执行完毕');
          console.log('成功：' + success + " 失败：" + fail);
          console.log(app.globalData.dimgs);
          wx.hideLoading();
          that.addItem();
        } else {//若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadCloudFiles(data);
        }
      }
    })
  },

  addItem(){
    let _this=this;
    let  db=wx.cloud.database();
    let val=this.data.val;
    let imgurls = app.globalData.dimgs;
    val.imgurls = imgurls;
    db.collection('tb_item_list').add({
      data:val,
      success:res=>{
        console.log(res)
      },
      fail:err=>{
        console.log(err)
      }
    })
  }
})